<!--重污染天气管控措施 enWeatherControlMeasure-->
<template>
  <Layout>
    <Form ref="form1" :model="dataToQuery" :label-width="120">
      <Row v-show="!switchFlag" class="query-form">
        <Col span="8">
          <FormItem label="企业名称：" prop="order">
            <cascader-dom class="query-form-el" ref='queryOrgCascader' @setOrgInfo='setQueryCompanyName' :orgTree="true"
                          :setCurrentName="{label:dataToQuery.companyName,value:dataToQuery.companyId}"></cascader-dom>
          </FormItem>
        </Col>
        <Col span="8">

        </Col>
        <Col span="8">
          <!--          <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>-->
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button type="primary" class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form">
        <Col span="8">
          <FormItem label="企业名称：" prop="belongOrgId">
            <cascader-dom class="query-form-el" ref='queryOrgCascader1' @setOrgInfo='setQueryCompanyName'
                          :orgTree="true"
                          :setCurrentName="{label:dataToQuery.companyName,value:dataToQuery.companyId}"></cascader-dom>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label='处罚类别：' prop='punishmentType'>
            <Select class='query-form-el' placeholder="请选择处罚类别" type='text' v-model='dataToQuery.punishmentTypeArrays'
                    multiple>
              <Option v-for="item in dictMap['ENEVT-000002']" :value="item.codingCodeId" :key="item.codingCodeId">
                {{ item.codingName }}
              </Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="事件发生时间：" prop="content">
            <DatePicker class="query-form-el" v-model="dataToQuery.dateRange" format="yyyy-MM-dd" type="daterange"
                        placement="bottom-end" placeholder="请选择查询时间段"
                        @on-change="(data)=> {this.onSelectFieldQueryDateRange(data, 'eventDate')}"></DatePicker>
          </FormItem>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form">
        <Col span="8">
          <FormItem label="填表时间：" prop="content">
            <DatePicker class="query-form-el" v-model="dataToQuery.dateRange" format="yyyy-MM-dd" type="daterange"
                        placement="bottom-end" placeholder="请选择查询时间段"
                        @on-change="onSelectQueryDateRange"></DatePicker>
          </FormItem>
        </Col>
        <Col span="8" offset="8">
          <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
      </Row>
      <Row class="query-form">
        <Col span="24">
          <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>
          <Button type="primary" class="ivu-btn-add" icon="md-cloud-download" @click="exportFormSubmit">导出</Button>
        </Col>
      </Row>
    </Form>
    <Table ref='table' :height="tableHeight" no-data-text="没有查询到相关数据!" @on-selection-change='getSelectRows'
           :loading='pageStatus.loading'
           border :columns="columns1" :data="dataTable">
    </Table>
    <Row style="margin-right:10px;">
      <Col span="24">
        <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange"
              @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray" show-total show-sizer
              show-elevator/>
      </Col>
    </Row>
    <Modal title="重污染天气管控措施" :transfer=false :mask-closable="false" v-model="dialogShow" v-if="dataToView && dialogShow" :width=800
           class-name='limit-height-dialog'>
      <Row>
        <Col span="24">
          <Form ref="dialogForm" :class="mode === 'view'?'modal-view-detail':''" :show-message="false"
                :model="dataToView" :rules="mode === 'view'?{}:ruleCustom" :label-width="mode === 'view'?190:null"
                :label-position="mode === 'view'?'right':'top'">
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label='所属单位：' prop='companyName'>
                  <div v-if="mode === 'view'">{{ dataToView.companyName }}</div>
                  <cascader-dom v-else ref='orgCascader'
                                @setOrgInfo='(data)=>{cascaderDomIdChangeHandle(data,"companyId");}'
                                @setOrgname='(data)=>{cascaderDomNameChangeHandle(data,"companyName");}'
                                :orgTree="true" :currentOrgId="dataToView.eventOrgId"
                                :setCurrentName="{label:dataToView.companyName,value:dataToView.companyId}">
                  </cascader-dom>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label='二级集团：'>
                  <div v-if="mode === 'view'">{{ dataToView.twoLevelOrgName }}</div>
                  <Input v-else class='' readonly type='text' v-model='dataToView.twoLevelOrgName'></Input>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='备案时间：' prop='recordDate'>
                  <div v-if="mode === 'view'">{{ renderViewDate(dataToView.recordDate) }}</div>
                  <DatePicker v-else class="w" placeholder="请选择备案时间" v-model='dataToView.recordDate' ></DatePicker>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='是否修订：' prop='revised'>
                  <div v-if="mode === 'view'">{{revisedFormate(dataToView.revised) }}</div>
                  <Select v-else class='w' v-model="dataToView.revised" >
                    <Option value="1" >是</Option>
                    <Option value="2" >否</Option>
                  </Select>
                </FormItem>

              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='填报人：' >
                  <div v-if="mode === 'view'">{{ dataToView.createUserName }}</div>
                  <Input v-else class='' placeholder="请填写填报人"  readonly  type='text' v-model='dataToView.createUserName'></Input>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='填报时间：' >
                  <div v-if="mode === 'view'">{{ renderViewDate(dataToView.createDate) }}</div>
                  <DatePicker v-else class="w" readonly v-model='dataToView.createDate'  ></DatePicker>
                </FormItem>
              </Col>
            </Row>

            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem v-if="mode === 'view'" label="重污染天气管控措施附件：">
                  <div v-show="uploadList.length>0" v-for="(item,index) in uploadList" :key='item'>
                    <a @click="downloadFile(dataToView.id,item,index)"><span
                        style="color: #3399ff;margin-left: 5px">{{ item.fileName }}</span></a>
                    <Progress v-show="uploadListVisible[index]" :percent="uploadListPercent[index]"></Progress>
                  </div>
                </FormItem>
                <FormItem v-else label="重污染天气管控措施附件：" prop="uploadList">
                  <div>
                    <Upload ref="upload"
                            :before-upload="beforeUpload"
                            :show-upload-list="true"
                            :max-size="10240"
                            multiple
                            type="drag"
                            :action="fileUrl">
                      <div style="padding: 10px">
                        <Icon type="ios-cloud-upload" size="45" style="color: #3399ff"></Icon>
                        <p>点击将文件拖拽到这里上传</p>
                        <span style="font-size:8px;color: #797a64">支持扩展名：.rar .zip .doc .docx .pdf...</span>
                      </div>
                    </Upload>
                  </div>
                  <div v-show="uploadList.length>0" v-for="(item,index) in uploadList" :key='item'>
                    <a @click="downloadFile(dataToView.id,item,index)">{{ item.fileName }}</a>
                    <Button type="text" icon="md-trash" @click="remove1(item.id)"
                            style="margin-left: 5px;margin-bottom: 3px"/>
                    <Progress v-show="uploadListVisible[index]" :percent="uploadListPercent[index]"></Progress>
                  </div>
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button v-if="mode != 'view'" type="primary" class='ivu-btn-save' @click="submit('dialogForm')">确定</Button>
        <Button v-if="mode != 'view'" type="primary" class='ivu-btn-cancel' @click="handleCancel">取消</Button>
        <Button v-if="mode === 'view'" class='ivu-btn-save' @click="dialogShow=false">关闭</Button>
      </div>
    </Modal>
  </Layout>
</template>

<script>
import {Api} from '@/api/index.js'
import {formatDate} from '@/tools/index'
import _deepclone from 'lodash/cloneDeep'

var cascaderDom = () => import('@/components/cascader-dom.vue');
import pageCommonFunction from '@/components/pageCommonFunction.js'

export default {
  components: {
    cascaderDom,
  },
  data() {
    return {
      ...this.createCommonDataField(),
      columns1: [
        {title: '序号', width: 70, fixed: 'left', align: 'center', render: this.indexColumnsRender},
        { key:'companyName',title: '所属单位',  align: 'center' },
        { key:'recordDate',title: '备案时间',  align: 'center', render:this.renderCellDate},
        { key:'revised',title: '是否修订',  align: 'center', render:(h,params)=>{
            return h('span', this.revisedFormate(params.row.revised))
          } },
        { key:'createUserName',title: '填报人',  align: 'center' },
        { key:'createDate',title: '填报时间',  align: 'center', render:this.renderCellDate },
          { key:'twoLevelOrgName',title: '所属二级集团',  align: 'center' },

        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          width: 160,
          align: 'center',
          render: (h, params) => {
            if (this.currentUser.loginId === this.Common.admin || this.currentUser.userId === params.row.createUserId || this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
            || this.currentUser.userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined) {
              return h('div', [
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px',},
                  on: {
                    click: () => {
                      // this.viewData(params);
                      this.dataToView = JSON.parse(JSON.stringify(params.row));
                      this.getFiles()
                      this.mode = 'view'
                      this.dialogShow = true
                    }
                  }
                }, '详情'),
                h('Divider', {props: {type: 'vertical'}}, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  disabled: true,
                  style: {fontSize: '14px'},
                  on: {
                    click: () => {
                      this.dataToView = JSON.parse(JSON.stringify(params.row));


                      this.getFiles()
                      this.dialogShow = true
                      this.mode = 'edit'
                      this.add = false
                    }
                  }
                }, '修改'),
                h('Divider', {props: {type: 'vertical'}}, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: 'red'},
                  on: {
                    click: () => {
                      this.deleteData(params);
                    }
                  }
                }, '删除')
              ]);
            } else {
              return h('div', [
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px',},
                  on: {
                    click: () => {
                      this.dataToView = JSON.parse(JSON.stringify(params.row));
                      this.getFiles()
                      this.mode = 'view'
                      this.dialogShow = true
                    }
                  }
                }, '详情'),
                h('Divider', {props: {type: 'vertical'}}, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: '#c5c8ce'}
                }, '修改'),
                h('Divider', {props: {type: 'vertical'}}, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: '#c5c8ce'}
                }, '删除')
              ]);
            }
          }
        }
      ],
      ruleCustom: {
        companyName: [ { required: true, message: '请填写所属单位', trigger: 'change',}],
        twoLevelOrgName: [ { required: true, message: '请填写所属二级集团', trigger: 'change',}],
        recordDate: [ { required: true, message: '请填写备案时间', trigger: 'change',type:'date'}],
        revised: [ { required: true, message: '请填写是否修订', trigger: 'change',}],
        createUserName: [ { required: true, message: '请填写填报人', trigger: 'change',}],
        createDate: [ { required: true, message: '请填写填报时间', trigger: 'change',}],
      },
      tableHeight: 10,
      uploadListVisible: [],
      uploadListPercent: [],
      dictMap: {},
      dataToView: {},
      uploadList: [],
      measureModel: false,
      // api
      queryUrl: Api.queryEnWeatherControlMeasure,
      deleteUrl: Api.deleteEnWeatherControlMeasure,
      updateUrl: Api.updateEnWeatherControlMeasure,
      saveUrl: Api.saveEnWeatherControlMeasure,

      exportUrl: Api.downloadEnWeatherControlMeasure,
    }
  },
  async mounted() {
    this.setTableHeight();
    this.query();
  },
  methods: {
    ...pageCommonFunction,
    deleteData(params) {
      this.deleteDateAjax(params);
    },
    formatePlanDate(startDate, endDate) {
      if (startDate && endDate) {
        return formatDate(new Date(startDate), 'yyyy-MM-dd') + "~" + formatDate(new Date(endDate), 'yyyy-MM-dd')
      } else {
        return "--";
      }

    },
    openSelect() {
      this.measureModel = true
    },
    query() {
      if (this.dataToQuery.punishmentTypeArrays) {
        this.dataToQuery.punishmentTypes = this.arrayToInFormat(this.dataToQuery.punishmentTypeArrays)
      }
      this.queryAjax();
    },
    revisedFormate(data){
      if (data){
        if (data == '1'){
          return "是";

        }else{
          return "否";
        }
      }else {
        return "";
      }
    },
    submit(name) {
      if (this.uploadList.length < 1) {
        this.$Message.error('请上传附件!');
      } else {
        this.submitAjax(name);
      }

    },

    addInfo() {
      this.dataToView = {};
      this.uploadList = [];
      this.dataToView = (this.createEmptyDataToAdd instanceof Function) ? this.createEmptyDataToAdd() : {};
      this.dataToView.companyId = this.currentUser.companyId;
      this.dataToView.companyName = this.currentUser.companyName;
      this.dataToView.belongOrgId = this.currentUser.twoLevelOrgId;
      this.dataToView.belongOrgName = this.currentUser.twoLevelOrgName;
      this.dataToView.registrant = this.currentUser.userName;
      this.dataToView.registrantPhone = this.currentUser.mobileNumber;
      this.dataToView.registTime = new Date();
      this.dataToView.id = this.get_uuid();
      this.mode = 'add'
      this.dialogShow = true;
      setTimeout(() => {
        this.dialogVisibleChangeHandele(this.dialogShow)
      }, 100)
    },
    selectMission(row) {

      this.measureModel = false;
      this.dataToView.measureName = row.emName;
      this.dataToView.measureId = row.emId;


    },
    downloadFile(guideId, file, index) {
      let url = this.fileUrl + '/file/' + file.id;
      var _this = this;
      this.uploadListVisible[index] = true;
      this.$http.get(url, {
        responseType: 'blob',      //告诉服务器我们需要的响应格式
        progress: function (e) {
          _this.$set(_this.uploadListPercent, index, 100 * (e.loaded / e.total));
        }
      }).then((res) => {
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = file.fileName //标题
        aLink.click()
        document.body.appendChild(aLink)
      })
    },
    remove1(id) {
      let url = this.fileUrl + '/file/' + id;
      this.$http.delete(url).then((res) => {
        this.getFiles()
      })
    },
    beforeUpload(file) {
      let formData = new FormData();
      formData.append("files", file); // 文件对象
      let url = this.fileUrl + '/' + this.dataToView.id + '/files/guideFile'
      this.$http.post(url, formData).then((res) => {
        if (res.data.result == "success") {
          this.$Message.info("文件上传成功")
          this.getFiles();
        }
      });
      return false
    },
    getFiles() {
      let url = this.fileUrl + '/' + this.dataToView.id + '/files/guideFile'
      this.$http.get(url).then((res) => {
        if (res.data.result == "success") {
          this.uploadList = res.data.data
          let index = 0;
          this.uploadList.forEach(item => {
            this.uploadListPercent[index] = 0;
            this.uploadListVisible[index] = false;
            index++;
          })
        }
      })
    },
    get_uuid() {
      let s = [];
      let hexDigits = "0123456789abcdef";
      for (let i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4";
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
      s[8] = s[13] = s[18] = s[23] = "-";

      let uuid = s.join("");
      let reg = new RegExp("-", "g");
      let a = uuid.replace(reg, "");
      return a;
    },
    handleCancel() {
      this.dataToView = {};
      this.dialogShow = false;
      this.query();
    },
    formatDate(date, fmt) {
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      };
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          let str = o[k] + '';
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
        }
      }
      return fmt;
    },
    padLeftZero(str) {
      return ('00' + str).substr(str.length);
    },
    createEmptyDataToAdd() {
      return {
        id: this.get_uuid(),
        createUserName: this.currentUser.userName,
        phone: this.currentUser.mobileNumber,
        twoLevelOrgId: this.currentUser.twoLevelOrgId,
        twoLevelOrgName: this.currentUser.twoLevelOrgName,
        createDate:new Date(),
        planDate: [],
      }
    }
  },
  watch: {},
}
</script>

<style lang='css' scoped>
@import '../../../../index.css';
</style>
